package com.sidianzhong.sdz.controller;

import com.alibaba.fastjson.JSONObject;
import com.sidianzhong.sdz.annotation.BackLoginToken;
import com.sidianzhong.sdz.annotation.UserLoginToken;
import com.sidianzhong.sdz.model.*;
import com.sidianzhong.sdz.service.*;
import com.sidianzhong.sdz.service.commond.RedisService;
import com.sidianzhong.sdz.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

/**
 * Created by hxg on 2016/10/06.
 */
@Api(description = "还款记录")
@Controller
public class RepaymentController {

    @Autowired
    RepaymentService repaymentService;
    @Autowired
    BorrowMoneyService borrowMoneyService;

    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @BackLoginToken
    @ApiOperation(value = "创建'还款记录'表中一条信息")
    @RequestMapping(value = "/repayment/new", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object createRepayment(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "borrowId", required = false) Integer borrowId,
            @RequestParam(value = "periods", required = false) Integer periods,
            @RequestParam(value = "repayAmount", required = false) Double repayAmount,
            @RequestParam(value = "defaults", required = false) Double defaults,
            @RequestParam(value = "serviceCharge", required = false) Double serviceCharge,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "createTime", required = false) String createTime,
            @RequestParam(value = "lastUpdateTime", required = false) String lastUpdateTime
    ) {
        Repayment item = new Repayment();
        Date date = new Date();
        if (userId != null) {
            item.setUserId(userId);
        }
        if (borrowId != null) {
            item.setBorrowId(borrowId);
        }
        if (periods != null) {
            item.setPeriods(periods);
        }
        if (repayAmount != null) {
            item.setRepayAmount(repayAmount);
        }
        if (defaults != null) {
            item.setDefaults(defaults);
        }
        if (serviceCharge != null) {
            item.setServiceCharge(serviceCharge);
        }
        if (status != null) {
            item.setStatus(status);
        }
        item.setCreateTime(new Date());
        item.setLastUpdateTime(new Date());
        Repayment iteams = repaymentService.create(item);
        boolean result = iteams != null;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @BackLoginToken
    @ApiOperation(value = "删除'还款记录'表中的某条记录")
    @RequestMapping(value = "/repayment/delete", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object deleteRepayment(
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "id") Integer id
    ) {
        Repayment item = repaymentService.get(id);
        if (null == item) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        int delete = repaymentService.delete(id);
        boolean result = delete != 0;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @BackLoginToken
    @ApiOperation(value = "修改'还款记录'表中的某条记录")
    @RequestMapping(value = "/repayment/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object editRepayment(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "id") Integer id,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "borrowId", required = false) Integer borrowId,
            @RequestParam(value = "periods", required = false) Integer periods,
            @RequestParam(value = "repayAmount", required = false) Double repayAmount,
            @RequestParam(value = "defaults", required = false) Double defaults,
            @RequestParam(value = "serviceCharge", required = false) Double serviceCharge,
            @RequestParam(value = "status", required = false) Integer status
    ) {
        Repayment item = repaymentService.get(id);
        if (null == item) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        if (userId != null) {
            item.setUserId(userId);
        }
        if (borrowId != null) {
            item.setBorrowId(borrowId);
        }
        if (periods != null) {
            item.setPeriods(periods);
        }
        if (repayAmount != null) {
            item.setRepayAmount(repayAmount);
        }
        if (defaults != null) {
            item.setDefaults(defaults);
        }
        if (serviceCharge != null) {
            item.setServiceCharge(serviceCharge);
        }
        if (status != null) {
            item.setStatus(status);
        }
        item.setLastUpdateTime(new Date());
        int update = repaymentService.update(item);
        boolean result = update != 0;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "查询'还款记录'表中的某条记录")
    @RequestMapping(value = "/getRepaymentById", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getRepaymentById(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "id") Integer id
    ) {
        Repayment item = repaymentService.get(id);
        if (null == item) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResultModel.ok(item), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "查询'还款记录'表中的多条记录返回对象")
    @RequestMapping(value = "/repayments", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getRepayments(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "sortItem", required = false, defaultValue = "id") String sortItem,
            @RequestParam(value = "sortOrder", required = false, defaultValue = "desc") String sortOrder,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "borrowId", required = false) Integer borrowId,
            @RequestParam(value = "periods", required = false) Integer periods,
            @RequestParam(value = "repayAmount", required = false) Double repayAmount,
            @RequestParam(value = "defaults", required = false) Double defaults,
            @RequestParam(value = "serviceCharge", required = false) Double serviceCharge,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "createTime", required = false) String createTime,
            @RequestParam(value = "lastUpdateTime", required = false) String lastUpdateTime
    ) {
        Repayment item = new Repayment();
        if (userId != null) {
            item.setUserId(userId);
        }
        if (borrowId != null) {
            item.setBorrowId(borrowId);
        }
        if (periods != null) {
            item.setPeriods(periods);
        }
        if (repayAmount != null) {
            item.setRepayAmount(repayAmount);
        }
        if (defaults != null) {
            item.setDefaults(defaults);
        }
        if (serviceCharge != null) {
            item.setServiceCharge(serviceCharge);
        }
        if (status != null) {
            item.setStatus(status);
        }
        if (createTime != null) {
            item.setCreateTime(Tools.convertStringToDate(createTime, "yyyy-MM-dd HH:mm:ss"));
        }
        if (lastUpdateTime != null) {
            item.setLastUpdateTime(Tools.convertStringToDate(lastUpdateTime, "yyyy-MM-dd HH:mm:ss"));
        }
        PageInfo<Repayment> list = repaymentService.getListWithPaging(pageNum, pageSize, sortItem, sortOrder, item);
        return new ResponseEntity<>(ResultModel.ok(list), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "查询'还款记录'表中的多条记录返回自定义JSONObject")
    @RequestMapping(value = "/repaymentsObject", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getRepaymentsObject(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "sortItem", required = false, defaultValue = "id") String sortItem,
            @RequestParam(value = "sortOrder", required = false, defaultValue = "desc") String sortOrder,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "borrowId", required = false) Integer borrowId,
            @RequestParam(value = "periods", required = false) Integer periods,
            @RequestParam(value = "repayAmount", required = false) Double repayAmount,
            @RequestParam(value = "defaults", required = false) Double defaults,
            @RequestParam(value = "serviceCharge", required = false) Double serviceCharge,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "createTime", required = false) String createTime,
            @RequestParam(value = "lastUpdateTime", required = false) String lastUpdateTime
    ) {
        Repayment item = new Repayment();
        if (userId != null) {
            item.setUserId(userId);
        }
        if (borrowId != null) {
            item.setBorrowId(borrowId);
        }
        if (periods != null) {
            item.setPeriods(periods);
        }
        if (repayAmount != null) {
            item.setRepayAmount(repayAmount);
        }
        if (defaults != null) {
            item.setDefaults(defaults);
        }
        if (serviceCharge != null) {
            item.setServiceCharge(serviceCharge);
        }
        if (status != null) {
            item.setStatus(status);
        }
        if (createTime != null) {
            item.setCreateTime(Tools.convertStringToDate(createTime, "yyyy-MM-dd HH:mm:ss"));
        }
        if (lastUpdateTime != null) {
            item.setLastUpdateTime(Tools.convertStringToDate(lastUpdateTime, "yyyy-MM-dd HH:mm:ss"));
        }
        PageInfo<JSONObject> list = repaymentService.getListWithObject(pageNum, pageSize, sortItem, sortOrder, item);
        List<JSONObject> list1 = list.getList();
        List<JSONObject> collect = list1.stream().map(ls -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", ls.getInteger("id"));
            jsonObject.put("userId", ls.getInteger("userId"));
            jsonObject.put("borrowId", ls.getInteger("borrowId"));
            jsonObject.put("periods", ls.getInteger("periods"));
            jsonObject.put("repayAmount", ls.getDouble("repayAmount"));
            jsonObject.put("defaults", ls.getDouble("defaults"));
            jsonObject.put("serviceCharge", ls.getDouble("serviceCharge"));
            jsonObject.put("status", ls.getInteger("status"));
            jsonObject.put("createTime", ls.getDate("createTime"));
            jsonObject.put("lastUpdateTime", ls.getDate("lastUpdateTime"));
            return jsonObject;
        }).collect(Collectors.toList());
        list.setList(collect);
        return new ResponseEntity<>(ResultModel.ok(list), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "我的还款")
    @RequestMapping(value = "/myRepayment", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object repayment(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "sortItem", required = false, defaultValue = "id") String sortItem,
            @RequestParam(value = "sortOrder", required = false, defaultValue = "desc") String sortOrder
            ) {
        Integer user_id = (Integer) request.getAttribute("USER_ID");

        //先查询出借款资格
        BorrowMoney borrowMoney = new BorrowMoney();
        borrowMoney.setUserId(user_id);
        borrowMoney.setStatus(0);
        List<BorrowMoney> list2 = borrowMoneyService.getList(pageNum, pageSize, sortItem, sortOrder, borrowMoney);
        if (list2.size() == 0) {
            return new ResponseEntity<>(ResultModel.error("没有借款记录"), HttpStatus.OK);
        }
        if (list2.size() > 1) {
            return new ResponseEntity<>(ResultModel.error("账号异常"), HttpStatus.OK);
        }
        BorrowMoney borrowMoney1 = list2.get(0);

        //查询出已还款的记录
        Repayment item = new Repayment();
        item.setUserId(user_id);
        item.setBorrowId(borrowMoney1.getId());
        item.setStatus(0);
        PageInfo<JSONObject> list = repaymentService.getListWithObject(pageNum, pageSize, sortItem, sortOrder, item);
        List<JSONObject> list1 = list.getList();
        if (list1.size() == 0) {
            return new ResponseEntity<>(ResultModel.ok(list), HttpStatus.OK);
        }
        List<JSONObject> collect = list1.stream().map(ls -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("periods", ls.getInteger("periods"));
            double repayAmount = ls.getDouble("repayAmount") + ls.getDouble("defaults");
            jsonObject.put("repayAmount", repayAmount);
            jsonObject.put("status", ls.getInteger("status"));
            jsonObject.put("createTime", ls.getDate("createTime"));
            return jsonObject;
        }).collect(Collectors.toList());

        List<JSONObject> collect1 = collect;

        //贷款编号
        String borrowNum = borrowMoney1.getBorrowNum();
        //已还款期数
        Integer periods = collect1.size();
        //总期数
        Integer totalPeriods = collect1.size();
        //最后还款日
        Date repayAmountTime = new Date(borrowMoney1.getCreateTime().getTime() + ((86400 * 1000 * 30) * periods));
        //本期还款数量
        Double repayAmount = borrowMoney1.getBorrowAmount() / totalPeriods;

        //超时罚息
        Date date = new Date();
        if (repayAmountTime.getTime() > date.getTime()) {
            repayAmount += 100;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("periods", periods);
        jsonObject.put("totalPeriods", totalPeriods);
        jsonObject.put("repayAmountTime", repayAmountTime);
        jsonObject.put("repayAmount", repayAmount);
        jsonObject.put("borrowNum", borrowNum);
        jsonObject.put("list", collect1);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "还款")
    @RequestMapping(value = "/repayment", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object repayment(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "borrowId", required = false) Integer borrowId,
            @RequestParam(value = "periods", required = false) Integer periods,
            @RequestParam(value = "repayAmount", required = false) Double repayAmount,
            @RequestParam(value = "defaults", required = false) Double defaults,
            @RequestParam(value = "serviceCharge", required = false) Double serviceCharge,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "createTime", required = false) String createTime,
            @RequestParam(value = "lastUpdateTime", required = false) String lastUpdateTime
    ) {
        Integer user_id = (Integer) request.getAttribute("USER_ID");

        //获取贷款
        BorrowMoney borrowMoney = borrowMoneyService.get(borrowId);
        if (borrowMoney == null) {
            return new ResponseEntity<>(ResultModel.error("贷款存单无效"), HttpStatus.OK);
        }
        if (borrowMoney.getStatus() != 0) {
            return new ResponseEntity<>(ResultModel.error("贷款存单已完成，请勿重复还款"), HttpStatus.OK);
        }

        //计算出这一期需要还款的本金
        Double borrowAmount = Double.valueOf(borrowMoney.getBorrowNum()) / borrowMoney.getBorrowAmount();


        //计算出是否超时

        Repayment item = new Repayment();
        Date date = new Date();

        item.setUserId(user_id);
        if (borrowId != null) {
            item.setBorrowId(borrowId);
        }
        if (periods != null) {
            item.setPeriods(periods);
        }
        if (repayAmount != null) {
            item.setRepayAmount(repayAmount);
        }
        if (defaults != null) {
            item.setDefaults(defaults);
        }
        if (serviceCharge != null) {
            item.setServiceCharge(serviceCharge);
        }
        if (status != null) {
            item.setStatus(status);
        }
        item.setCreateTime(new Date());
        item.setLastUpdateTime(new Date());
        Repayment iteams = repaymentService.create(item);
        boolean result = iteams != null;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }
}
